package controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Glossario;
import model.Login;
import model.Termo;

import persistence.TermosDao;
import persistence.TermosDaoImpl;

@WebServlet("/gravar")
public class GravarServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public GravarServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String saida = "";
		String erro = "";
		Login login = new Login();
		List<Glossario> termosCadastrados = new ArrayList<Glossario>();
		TermosDao tDao = new TermosDaoImpl();
		Termo t = new Termo();
		if (request.getParameter("enviar") == null){
			//Excluir
			t.setId(Integer.parseInt(request.getParameter("param1")));
			ListaCadastrados listaCadastrados = new ListaCadastrados();
			login.setNomeCompleto(request.getParameter("param2"));
			login.setSenha(request.getParameter("param3"));
			try {
				saida = tDao.excluiTermo(t);
				termosCadastrados = listaCadastrados.listaCadastrados(login);
			} catch (SQLException e) {
				erro = e.getMessage();
			}
			//TODO Editar
		} else {
			//Cadastrar
			
			t.setRa(request.getParameter("ra"));
			t.setTermo(request.getParameter("texto"));
			t.setTermoOriginal(request.getParameter("textooriginal"));
			t.setNomeTermo(request.getParameter("termo"));
			t.setNomeTermoOriginal(request.getParameter("termooriginal"));
			t.setFonte(request.getParameter("fonte"));
			login.setNomeCompleto(request.getParameter("nome"));
			login.setSenha(t.getRa());
			
			ListaCadastrados listaCadastrados = new ListaCadastrados();
			
			try {
				saida = tDao.cadastraTermo(t);
				
				termosCadastrados = listaCadastrados.listaCadastrados(login);
			} catch (SQLException e) {
				erro = e.getMessage();
			}
		}
		request.setAttribute("erro", erro);
		request.setAttribute("mensagem", saida);
		request.setAttribute("login", login);
		request.setAttribute("termosCadastrados", termosCadastrados);
		RequestDispatcher view = request.getRequestDispatcher("cadastro.jsp");
		view.forward(request, response);
	}
	
}
